#define ADC_PIN 35   // ESP32的ADC引脚
#define FILTER_SIZE 10  // 滤波缓冲区大小
#define ADJUSTER 3.3 / 4095.0 // ADC值转电压的调整因子

int filterBuffer[FILTER_SIZE] = {0}; // 初始化缓冲区
int filterIndex = 0;
long filterSum = 0; // 缓冲区的总和

void setup() {
  Serial.begin(115200);  // 初始化串口通信
}

// 滑动窗口平均滤波函数
int applyFilter(int newValue) {
  filterSum -= filterBuffer[filterIndex];
  filterSum += newValue;
  filterBuffer[filterIndex] = newValue;
  filterIndex = (filterIndex + 1) % FILTER_SIZE;
  return filterSum / FILTER_SIZE;
}

// 判断开关状态的函数
String determineStatus(float voltage) {
  return (voltage < 1.65) ? "High" : "Low";
}

void loop() {
  // 读取油门开关的状态
  int analogValue = analogRead(ADC_PIN);
  float voltage = analogValue * ADJUSTER;

  // 应用滑动窗口平均滤波
  int filteredAnalogValue = applyFilter(analogValue);
  float filteredVoltage = filteredAnalogValue * ADJUSTER;

  // 判断开关状态
  String status = determineStatus(filteredVoltage);

  // 通过串口输出开关状态
  Serial.print("Status: ");
  Serial.print(status);
  Serial.print(" (Filtered Voltage: ");
  Serial.print(filteredVoltage, 2);
  Serial.print(" V, Filtered Raw: ");
  Serial.print(filteredAnalogValue);
  Serial.print(" | Raw Voltage: ");
  Serial.print(voltage, 2);
  Serial.print(" V, Raw: ");
  Serial.print(analogValue);
  Serial.println(")");

  delay(500); // 延时以便读取变化
}